package net.gyapp.markim.core;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.easyder.wrapper.core.network.ResponseCallback;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.xuhao.android.libsocket.utils.Logger;

import net.gyapp.markim.core.reponse.ImResponse;

import org.jim.common.base.ImPacket;

import java.io.File;
import java.util.List;

/**
 * Author:  winds
 * Data:    2018/7/17
 * Version: 1.0
 * Desc:    数据包解析
 */


public class ResponseParser {

    public static <T extends ImResponse> T parse(ImPacket packet, Class<T> clz) {
        try {
            return parseData(new String(packet.getBody(), "utf-8"), clz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据对象类型解析数据
     *
     * @param json Json字符串
     * @param clz  对象类型
     * @param <T>  对象泛型
     * @return
     */
    private static <T extends ImResponse> T parseData(String json, Class<T> clz) {
        if (TextUtils.isEmpty(json) || clz == null) {
            Logger.i(" -- ResponseChanged -- ", String.format("%1$s%2$s%3$s%4$s", " ResponseChanged is empty ? ", TextUtils.isEmpty(json), " clz == null ? ", clz == null));
            return null;
        }
        T bean;
        try {
            if (json.startsWith("[")) {
                bean = clz.newInstance();
                List<?> dataSet = JSON.parseArray(json, bean.elementType());
                bean.setDataList(dataSet);
            } else {
                bean = JSON.parseObject(json, clz);
            }
        } catch (Exception ex) {
            Logger.i(" -- ResponseChanged -- ", " Parse Error");
            throw new JSONException("数据解析失败! Exception: " + ex.getMessage());
        }
        return bean;
    }



}
